<!--
  @author:  long
  @date:    2023/6/15
  @file:    xx
  @require:
-->
<template>
  <div>
    <TitleName title="代账信息" icon="i-carbon-bookmark-filled"></TitleName>
    <div class="px-5 pt-5">
      <el-descriptions :column="column" border>
        <el-descriptions-item
          v-for="(item, index) in cols"
          :key="index"
          :label="item.label + ':'"
          label-align="right"
          label-class-name="w-5/24"
          class-name="w-7/24"
        >
          <template
            v-if="
              item.prop == 'agentAgreementFile' || item.prop == 'agentStarPic'
            "
          >
            <el-button
              type="primary"
              link
              @click="viewFile(form[item.prop][0].url)"
            >
              {{
                form[item.prop] != null ? form[item.prop][0].origFileName : ''
              }}</el-button
            >
          </template>
          <!--      星级      -->
          <template v-else-if="item.prop == 'starRating'">
            <el-rate v-model="form[item.prop]" disabled />
          </template>
          <!--      合作产品      -->
          <template v-else-if="item.prop == 'agentBusinessTypeId'">
            <dict-tag
              :options="business_classification"
              :value="form[item.prop]"
            />
          </template>
          <!--      收取率      -->
          <template v-else-if="item.prop == 'percentage'">
            {{
              customerShareData.totalNum != null &&
              customerShareData.dealSucNum != null
                ? (
                    (customerShareData.dealSucNum /
                      customerShareData.totalNum) *
                    100
                  ).toFixed(2) + '%'
                : '-'
            }}
          </template>
          <template v-else>
            <span>{{ form[item.prop] }}</span>
          </template>
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <div>
      <div class="flex items-center">
        <TitleName
          class="my-5"
          title="下属企业"
          icon="i-carbon-bookmark-filled"
        ></TitleName>

        <div class="text-xl pt-2 ml-5">
          总户数：{{ customerShareData.totalNum }}
        </div>
        <div class="text-xl pt-2 ml-5">
          已到账户数：{{ customerShareData.dealSucNum }}
        </div>
      </div>

      <div class="mb-3 flex items-center">
        <el-button
          type="primary"
          icon="Delete"
          size="small"
          @click="handleDeleteAccounting"
          >删除</el-button
        >
        <el-button
          type="primary"
          plain
          size="small"
          icon="Document"
          @click="fetchFile"
          >下载模板</el-button
        >

        <el-upload
          class="upload-demo"
          action="#"
          :http-request="
            params => {
              handleFileChange(params)
            }
          "
          accept=".xlsx, .xls"
          :show-file-list="false"
        >
          <el-button
            class="mx-4"
            type="primary"
            plain
            icon="Upload"
            size="small"
            >导入</el-button
          >
        </el-upload>
        <el-button
          type="primary"
          plain
          icon="Download"
          size="small"
          @click="exportQuery"
          >导出</el-button
        >
        <el-button type="primary" plain size="small" @click="confirmProfit"
          >确认分润</el-button
        >
        <el-button type="primary" plain size="small" @click="invertProfit"
          >反选分润</el-button
        >
        <el-input
          v-model="agentNameOrtaxCode"
          placeholder="请输入名称或者税号"
          class="w-100 ml-5"
          clearable
          size="small"
          @keydown.enter="handleQuery"
        ></el-input>
        <el-select
          v-model="dealStatus"
          class="m-2"
          placeholder="到账情况"
          size="small"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="item in accountOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="shareStatus"
          class="m-2"
          placeholder="分润情况"
          size="small"
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="item in profitOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button
          type="primary"
          icon="Search"
          size="small"
          @click="handleQuery"
          >查询</el-button
        >
      </div>
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        @row-dblclick="handleRowDblclick"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column width="30" align="center">
          <template #default="scope">
            <span v-if="scope.row.isCustomerId != null">
              <svg-icon
                :icon-class="'customer'"
                class="block w-20px h-20px m-auto mb-15px"
              />
            </span>
          </template>
        </el-table-column>
        <el-table-column
          property="agentName"
          label="公司名称"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.agentName }}
          </template>
        </el-table-column>
        <el-table-column
          property="taxCode"
          label="税号"
          show-overflow-tooltip
        />
        <el-table-column prop="custType" label="企业性质" width="130">
          <template #default="scope">
            {{ custType[scope.row.custType] }}
          </template>
        </el-table-column>
        <el-table-column label="数电配置" width="100">
          <template #default="scope">
            {{
              scope.row.isDigital == '1'
                ? '已配置'
                : scope.row.isDigital == '0'
                ? '未配置'
                : '未知'
            }}
          </template>
        </el-table-column>

        <el-table-column prop="dealAmount" label="到账金额" width="100" />
        <el-table-column label="到账情况" width="100">
          <template #default="scope">
            {{ scope.row.dealStatus == '1' ? '已成功' : '未成功' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="dueEndTime"
          label="服务到期时间"
          :formatter="dateFormat"
        >
        </el-table-column>
        <el-table-column label="分润情况" width="100">
          <template #default="scope">
            {{ scope.row.shareStatus == '1' ? '已分润' : '未分润' }}
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script setup name="AccountingSituation">
import { getCurrentInstance, watch } from 'vue'
import { getCustomerEditInfo } from '@/api/customerManage/customerList'
import { viewFile } from '@/utils/commo'
import {
  deleteAccounting,
  getAccountingList,
  getCustomerShareMsg,
  importAccountingData,
  saveAccountingInfo
} from '@/api/customerManage/accounting'
import { format } from 'date-fns'
import { useRoute } from 'vue-router'
import useTagsViewStore from '@/store/modules/tagsView'

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
import useCommonStore from '@/store/modules/common'
const commonStore = useCommonStore()

const data = reactive({
  queryParams: {
    pageSize: 10,
    pageNum: 1
  },
  form: {
    agentAgreementFile: [{ origFileName: '', url: '' }], //代账公司合同
    agentAuthorizationCode: '', //授权码
    agentIncomeMoney: '', //代账公司每户收取金额
    agentShareMoney: '', //代账公司每户分润金额
    agentStarAwardEdate: '', //星级授牌到期时间
    agentStarAwardSdate: '', //星级授牌时间
    agentStarPic: [{ origFileName: '', url: '' }] //代账公司授牌照片
  },
  cols: [
    { prop: 'agentAuthorizationCode', label: '授权码' },
    { prop: 'scale', label: '代账公司规模' },
    { prop: 'starRating', label: '代账公司星级' },
    { prop: 'agentStarAwardDate', label: '星级授牌时间' },
    { prop: 'agentIncomeMoney', label: '代账公司每户收取金额' },
    { prop: 'agentShareMoney', label: '代账公司每户分润金额' },
    { prop: 'agentAgreementFile', label: '代账公司合同' },
    { prop: 'agentStarPic', label: '代账公司授牌照片' },
    { prop: 'expectAccount', label: '预计总收益' },
    { prop: 'expectShareAmount', label: '预计分润金额' },
    { prop: 'account', label: '实际收益' },
    { prop: 'shareAmount', label: '实际分润' },
    { prop: 'agentBusinessTypeId', label: '合作产品' },
    { prop: 'percentage', label: '收取率' }
  ],
  column: 2,
  accountOptions: [
    { label: '已成功', value: '1' },
    { label: '未成功', value: '0' }
  ],
  profitOptions: [
    { label: '已分润', value: '1' },
    { label: '未分润', value: '0' }
  ],
  shareStatus: '', //分润状态：0-未分润，1-已分润
  dealStatus: '', //交易状态：0-未成功，1-成功
  agentNameOrtaxCode: '', //代账公司名称或税号
  tableData: [],
  total: 0,
  selectionData: [],
  customerName: '',
  custType: {
    0: '一般纳税人',
    1: '小规模纳税人',
    2: '点下户',
    3: '非纳税人'
  }
})
const {
  form,
  cols,
  column,
  accountOptions,
  profitOptions,
  shareStatus,
  dealStatus,
  agentNameOrtaxCode,
  queryParams,
  tableData,
  total,
  selectionData,
  customerName,
  custType
} = toRefs(data)

// 代账公司统计数据信息
const customerShareData = ref({
  dealSucNum: 0,
  totalNum: 0
})

// 字典 具体查看根目录DICT.md文件
const { business_classification } = proxy.useDict('business_classification')
const emit = defineEmits(['handleReplace'])
/**
 * 表格双击跳转客户详情
 */
const handleRowDblclick = row => {
  if (row.isCustomerId) {
    emit('handleReplace', row.isCustomerId)
  }
}

/** 下载模板操作 */
const fetchFile = async () => {
  const url = await commonStore.getUploadTemplateDown(
    'accountingSituation_file_down'
  )
  window.open(url, '_blank')
}

const dateFormat = (row, column) => {
  let date = row[column.property]
  console.info('date', column)
  if (date === undefined || date == null) {
    return ''
  }
  return date.substring(0, 10)
}

/**
 * 确认分润
 */
const confirmProfit = () => {
  if (selectionData.value.length == 0) {
    proxy.$modal.msgWarning('请选择要操作的数据')
    return
  }

  proxy.$modal
    .confirm('是否确认分润选中的数据？')
    .then(res => {
      let params = []
      selectionData.value.forEach(item => {
        item.shareStatus = '1'
        params.push(item)
      })
      saveAccountingInfo(params).then(res => {
        handleQuery()
        getCustomerShareMsgById()
      })
    })
    .catch(() => {})
}

/**
 * 反选分润
 */
const invertProfit = () => {
  if (selectionData.value.length == 0) {
    proxy.$modal.msgWarning('请选择要操作的数据')
    return
  }
  proxy.$modal
    .confirm('是否反选分润选中的数据？')
    .then(res => {
      let params = []
      selectionData.value.forEach(item => {
        item.shareStatus = item.shareStatus == '0' ? '1' : '0'
        params.push(item)
      })
      saveAccountingInfo(params).then(res => {
        handleQuery()
        getCustomerShareMsgById()
      })
    })
    .catch(() => {})
}

/**
 * 下属企业数据导出
 */
const exportQuery = () => {
  let params = {
    customerId: router.currentRoute.value.query.customerId,
    shareStatus: shareStatus.value, //分润状态：0-未分润，1-已分润
    dealStatus: dealStatus.value, //交易状态：0-未成功，1-成功
    agentNameOrtaxCode: agentNameOrtaxCode.value
  }

  proxy.downLoadByUrl(
    '/customer/generator/bizcustomeragent/outPutExcel',
    params,
    `${customerName.value}-下属企业信息.xlsx`
  )
}

/**
 * 删除客户
 */
function handleDeleteAccounting() {
  if (!selectionData.value.length) {
    proxy.$modal.msgWarning('请选择要删除的数据')
    return
  }
  proxy.$modal
    .confirm('是否确认删除选中的数据？')
    .then(res => {
      let ids = selectionData.value
        .map(item => {
          return item.agentId
        })
        .join(',')
      console.info('ids', ids)
      const params = {
        ids
      }
      deleteAccounting(params).then(res => {
        proxy.$modal.msgSuccess(res.msg)
        handleQuery()
        getCustomerShareMsgById()
      })
    })
    .catch(() => {})
}

async function handleFileChange(file) {
  console.info('file', file)
  let formData = new FormData()
  formData.append('file', file.file)
  let customerId = router.currentRoute.value.query.customerId

  try {
    const res = await importAccountingData(formData, customerId)
    if (res.code === 200) {
      proxy.$modal.msgSuccess('导入成功')
      handleQuery()
      getCustomerShareMsgById()
    }
  } catch (error) {
    console.log(error)
    proxy.$modal.msgError(error)
  }
}

/**
 * 代账公司下属公司表格多选
 */
const handleSelectionChange = val => {
  selectionData.value = val
}

/**
 * 查询事件
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
  // getCustomerShareMsgById()
}

/**
 * 代账公司子公司列表
 */
const getList = () => {
  let params = {
    customerId: router.currentRoute.value.query.customerId,
    shareStatus: shareStatus.value, //分润状态：0-未分润，1-已分润
    dealStatus: dealStatus.value, //交易状态：0-未成功，1-成功
    agentNameOrtaxCode: agentNameOrtaxCode.value,
    ...queryParams.value
  }
  getAccountingList(params).then(res => {
    tableData.value = res.data.records
    total.value = res.data.total
  })
}

/**
 * 获取代账公司交易信息
 */
const getCustomerShareMsgById = () => {
  let customerId = router.currentRoute.value.query.customerId
  getCustomerShareMsg(customerId).then(res => {
    console.info('res', res)
    customerShareData.value = res
    // 实际收益
    form.value.account = res.account
    //  已分润金额    已分润公司数量
    form.value.shareAmount = res.shareNum * form.value.agentShareMoney
    //预计总收益
    form.value.expectAccount = form.value.agentIncomeMoney * res.totalNum
    // 预计总分润
    form.value.expectShareAmount = form.value.agentShareMoney * res.totalNum
  })
}

/**
 * 代账公司信息
 */
const getCustomerEditInfoById = () => {
  let customerId = router.currentRoute.value.query.customerId

  //   代账公司信息
  getCustomerEditInfo(customerId).then(res => {
    customerName.value = res.data.bizCustomerAddDto.customerName
    form.value = res.data.bizCustomerExtDto
    form.value.agentStarAwardSdate =
      form.value.agentStarAwardSdate && form.value.agentStarAwardSdate != ''
        ? form.value.agentStarAwardSdate.substring(0, 10)
        : ''
    form.value.agentStarAwardEdate =
      form.value.agentStarAwardEdate && form.value.agentStarAwardEdate != ''
        ? form.value.agentStarAwardEdate.substring(0, 10)
        : ''
    //   代账公司星级
    form.value.starRating = res.data.bizCustomerAddDto.starRating
    //    星级授牌时间
    form.value.agentStarAwardDate =
      form.value.agentStarAwardSdate &&
      form.value.agentStarAwardSdate != '' &&
      form.value.agentStarAwardEdate &&
      form.value.agentStarAwardEdate != ''
        ? form.value.agentStarAwardSdate + '至' + form.value.agentStarAwardEdate
        : ''

    console.info('form.value', form.value)

    //代账公司交易信息
    getCustomerShareMsgById()

    //   代账公司子公司列表
    handleQuery()
  })
}

/**
 * 初始化
 */
const init = async () => {
  //代账公司信息
  await getCustomerEditInfoById()
}
init()
</script>

<style scoped lang="scss"></style>
